﻿using System.Text;
using System.Text.RegularExpressions;

namespace jinmaMesProxy.DataAccess
{
    public static class SqlView
    {
        private static void ExecSql(ErpDbInstance instance,string sql)
        {
            using (var cmd = instance.MakeQueryCommand(sql))
            {
                cmd.ExecuteNonQuery();
            }
        }
        public static void Setup()
        {
            var files = Directory.GetFiles(RuntimeVariable.ROOT_PATH + "/SETUPVIEW").Where(r=>r.EndsWith(".sql"));

            using (ErpDbInstance instance = new ErpDbInstance(ErpConfig.Default()))
            {
                foreach (var file in files)
                {
                    Logger.Log($"初始化{file}");
                    var sqlText = File.ReadAllText(file).Trim();
                    var batches = Regex.Split(sqlText,@"(?m)^\s*GO\s*$",RegexOptions.IgnoreCase);
                    foreach (var sql in batches)
                    {
                        if (string.IsNullOrWhiteSpace(sql.Trim()))
                            continue;
                        ExecSql(instance, sql.Trim());
                    }
                    File.Delete(file);
                }
                instance.Commit();
            }
        }
    }
}
